<?php
//百度图片提取文件 标准版

namespace app\service;

class BaiduExtractFiles
{
    public $app_key = '';
    public $secret_key = '';
    public $access_token = '';


    public function __construct()
    {
        $config = get_config_cache('baidu_extract_files');
        $this->app_key = $config['app_key'];
        $this->secret_key = $config['secret_key'];
    }

    public function run(string $img)
    {
        if(empty($img)){
            return '';
        }
        $img = urlencode(base64_encode(file_get_contents($img)));
        $access_token = $this->getBaiduExtractFilesAccessToken();

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=$access_token",
            CURLOPT_TIMEOUT => 30,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_SSL_VERIFYPEER  => false,
            CURLOPT_SSL_VERIFYHOST  => false,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => 'image='.$img.'&detect_direction=false&detect_language=false&paragraph=false&probability=false',
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/x-www-form-urlencoded',
                'Accept: application/json'
            ),
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }

    /**
     * 使用 AK，SK 生成鉴权签名（Access Token）
     * @return string 鉴权签名信息（Access Token）
     */
    public function getBaiduExtractFilesAccessToken()
    {
        $curl = curl_init();
        $postData = array(
            'grant_type' => 'client_credentials',
            'client_id' => $this->app_key,
            'client_secret' => $this->secret_key
        );
        curl_setopt_array($curl, [
            CURLOPT_URL => 'https://aip.baidubce.com/oauth/2.0/token',
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_SSL_VERIFYPEER  => false,
            CURLOPT_SSL_VERIFYHOST  => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => http_build_query($postData)
        ]);
        $response = curl_exec($curl);
        curl_close($curl);
        $rtn = json_decode($response);
        return $rtn->access_token;
    }
}